namespace DCHealthCheck.DomainModel {

    #region Usings
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Diagnostics;
    using System.IO;
    using System.Text; 
    #endregion

    [Table("GroupPolicySysvolInfo")]
    public class GroupPolicySysvolInfo : IGroupPolicySysvolInfo, IObjectWithState, IValidatableObject {

        #region Members
        #region Max length fields
        public static readonly int DisplayNameMaxLength = 255;
        public static readonly int DirectoryPathMaxLength = 255;
        public static readonly int VersionMaxLength = 255;
        #endregion

        public virtual DateTime CreatedUTC { get; set; }

        public static readonly string CSVHeader =
            "DCName,Domain,ADSite,OSVersion,HealthCheckDate," +
            "DirectoryPath,DisplayName,CreatedUTC,ModifiedUTC,Version";

        [Display(Name = "Directory")]
        public virtual string DirectoryPath { get; set; }

        [Display(Name = "GPO Display Name")]
        public virtual string DisplayName { get; set; }

        [Key]
        [ForeignKey("SystemInfo")]
        public virtual Guid Id { get; set; }

        public virtual DateTime ModifiedUTC { get; set; }

        public virtual string Version { get; set; }

        #region Related Entities
        public virtual SystemInfo SystemInfo {
            get { return systemInfo; }
            set {
                systemInfo = value;

                if (systemInfo != null) {
                    if (this.Id != systemInfo.Id) {
                        this.Id = systemInfo.Id;
                    }
                }
            }
        }
        private SystemInfo systemInfo;
        #endregion

        #region NotMapped properties
        [NotMapped]
        public DetachedState DetachedState { get; set; }

        [NotMapped]
        public string DirectoryName {
            get {
                if (string.IsNullOrWhiteSpace(this.DirectoryPath)) return string.Empty;
                return this.DirectoryPath.Replace(Path.GetDirectoryName(this.DirectoryPath), string.Empty).Replace(Path.DirectorySeparatorChar.ToString(), string.Empty);
            }
        }

        [NotMapped]
        public Object EntityKey { get { return this.Id; } }

        [NotMapped]
        public Dictionary<string, object> StartingOriginalValues { get; set; }
        #endregion 
        #endregion

        #region Constructor
        public GroupPolicySysvolInfo() {
            this.DirectoryPath = string.Empty;
            this.DisplayName = string.Empty;
            this.Version = string.Empty;
        } 
        #endregion

        #region Methods
        public string ToCSVString() {
            var info = new StringBuilder();

            #region DC Info
            if ((this.SystemInfo != null) && (this.SystemInfo.DomainController != null)) {
                info.AppendFormat("\"{0}\",", this.SystemInfo.DomainController.SamAccountNameFriendly);
                info.AppendFormat("\"{0}\",", this.SystemInfo.DomainController.NetbiosDomain);
                info.AppendFormat("\"{0}\",", this.SystemInfo.DomainController.ADSite);
                info.AppendFormat("\"{0}\",", this.SystemInfo.DomainController.OSVersion);
            }
            else {
                info.Append(",,,,");
            }
            #endregion

            if (this.SystemInfo != null) {
                info.AppendFormat("\"{0}\",", this.SystemInfo.CheckDateTimeUTC.ToString("yyyy-MM-dd HH:mm"));
            }
            else {
                info.Append(",");
            }

            info.AppendFormat("\"{0}\",", this.DirectoryPath);
            info.AppendFormat("\"{0}\",", this.DisplayName);
            info.AppendFormat("\"{0}\",", this.CreatedUTC.ToString("yyyy-MM-dd HH:mm"));
            info.AppendFormat("\"{0}\",", this.ModifiedUTC.ToString("yyyy-MM-dd HH:mm"));
            info.AppendFormat("\"{0}\",", this.Version);

            return info.ToString();
        }

        [DebuggerStepThroughAttribute]
        public override string ToString() {
            var info = new StringBuilder();

            info.AppendFormat("GroupPolicySysvolInfo: SystemInfo DC: {0}; GPO Directory: {1}",
                this.SystemInfo != null && this.SystemInfo.DomainController != null ? this.SystemInfo.DomainController.DNSName : "NULL",
                this.DirectoryPath != null ? this.DirectoryPath : "NULL");

            return info.ToString();
        }

        public string ToVerboseString() {
            var info = new StringBuilder();

            if ((this.SystemInfo != null) && (this.SystemInfo.DomainController != null) && (this.SystemInfo.DomainController.DNSName != null)) {
                info.AppendFormat("DC: {0}; ", this.SystemInfo.DomainController.DNSName);
            }
            if (this.SystemInfo != null) {
                info.AppendFormat("HealthCheck Date: {0}; ", this.SystemInfo.CheckDateTimeUTC.ToString("yyyy-MMM-dd"));
            }
            info.AppendFormat("GPO Display Name: {0}; ", this.DisplayName != null ? this.DisplayName : "NULL");
            info.AppendFormat("GPO Directory Path: {0}", this.DirectoryPath != null ? this.DirectoryPath : "NULL");

            return info.ToString();
        }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
            // add entity to SystemInfo, let DetectChanges perform relationship fixup
            if (this.Id == Guid.Empty) {
                yield return new ValidationResult(
                    "Id is required.", new[] { "Id" });
            }
            if (this.DetachedState != DetachedState.Deleted) {
                if (this.SystemInfo == null) {
                    yield return new ValidationResult(
                        "SystemInfo is required.", new[] { "SystemInfo" });
                }

                if (string.IsNullOrWhiteSpace(this.DirectoryName)) {
                    yield return new ValidationResult(
                        "DirectoryName is required.", new[] { "DirectoryName" });
                }
                else if (this.DirectoryPath.Length > DirectoryPathMaxLength) {
                    yield return new ValidationResult(string.Format("DirectoryPath length: {0} exceeds max length: {1}",
                        this.DirectoryPath.Length, DirectoryPathMaxLength), new[] { "DirectoryPath" });
                }

                if (string.IsNullOrWhiteSpace(this.DisplayName)) {
                    yield return new ValidationResult(
                        "DisplayName is required.", new[] { "DisplayName" });
                }
                else if (this.DisplayName.Length > DisplayNameMaxLength) {
                    yield return new ValidationResult(string.Format("DisplayName length: {0} exceeds max length: {1}",
                        this.DisplayName.Length, DisplayNameMaxLength), new[] { "DisplayName" });
                }

                if (string.IsNullOrWhiteSpace(this.Version)) {
                    yield return new ValidationResult(
                        "Version is required.", new[] { "Version" });
                }
                else if (this.Version.Length > VersionMaxLength) {
                    yield return new ValidationResult(string.Format("Version length: {0} exceeds max length: {1}",
                        this.Version.Length, VersionMaxLength), new[] { "Version" });
                }
            } // if (this.DetachedState != State.Deleted)
        }  
        #endregion
    }
}
